package com.yc.game.service.impl;

import com.yc.game.pojo.Cart;
import com.yc.game.pojo.Food;
import com.yc.game.service.CartService;
import com.yc.game.dao.CartMapper;
import com.yc.game.dao.FoodMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CartServiceImpl implements CartService {
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private FoodMapper foodMapper;

    /**
     * 添加减少商品到购物车
     * @param foodId
     * @param quantity
     * @param email
     * @return
     */
    @Override
    public int addCart(Integer foodId, Integer quantity, String email) {
        // 查询商品信息
        Food food = foodMapper.selectByPrimaryKey(foodId);
        // 判断购物车里面有没有这个商品
        Cart oloCart = cartMapper.getByFoodId(foodId);
        if (oloCart == null) {
            Cart newCart = new Cart();
            newCart.setFoodId(foodId);
            newCart.setFoodImg(food.getImgUrl());
            newCart.setFoodName(food.getFoodName());
            newCart.setPrice(food.getNowPrice());
            newCart.setQuantity(quantity);
            newCart.setTotalPrice(quantity * food.getNowPrice());
            newCart.setEmail(email);
            return cartMapper.insertSelective(newCart);
        }
        // 取出数量重新设置值
        Cart newCart = new Cart();
        newCart.setId(oloCart.getId());
        if (quantity == 1 || quantity == -1) {
            newCart.setQuantity(quantity + oloCart.getQuantity());
            newCart.setTotalPrice(quantity * food.getNowPrice() + oloCart.getTotalPrice());
            return cartMapper.updateByPrimaryKeySelective(newCart);
        }
        newCart.setQuantity(quantity);
        newCart.setTotalPrice(quantity * food.getNowPrice());
        return cartMapper.updateByPrimaryKeySelective(newCart);
    }

    /**
     * 根据邮箱获取购物车集合
     *
     * @param email
     * @return
     */
    @Override
    public List<Cart> getByEmail(String email) {

        return cartMapper.getByEmail(email);
    }

    /**
     * 根据购车id删除
     * @param cartId
     * @return
     */
    @Override
    public int deleteById(Integer cartId) {
        return cartMapper.deleteByPrimaryKey(cartId);
    }

}
